package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.admin.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 查询所有自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1 参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2 条件封装执行查询
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        // 文章标题模糊查询
        wrapper.like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        // 频道id
        wrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        // 文章状态
        wrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        // 发布时间 >= 开始时间
        wrapper.ge(dto.getBeginPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate());
        // 发布时间 <= 开始时间
        wrapper.le(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate());
        // 当前自媒体人文章
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        // 按照创建日期倒序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        // 分页条件构建
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //3 执行查询
        IPage<WmNews> pageResult = page(page, wrapper);
        //4 返回封装查询结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        result.setData(pageResult.getRecords());
        // 处理文章图片
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        // 1 参数校验
        if (StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 校验是否登陆
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2 保存或修改文章
        WmNews wmNews = new WmNews();
        // 将dto参数里面的值设置到wmNews
        BeanUtils.copyProperties(dto, wmNews);
        //如果文章布局是自动，需要设置为null
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        // 处理dto参数 images封面集合 转换成 字符串
        String images = imageListToStr(dto.getImages());
        wmNews.setImages(images);
        wmNews.setUserId(user.getId());
        saveWmNews(wmNews);
        // 如果是草稿  直接返回
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())) {
            return ResponseResult.okResult();
        }
        //3.1 抽取文章中关联的图片路径
        List<String> materials = parseContentImages(dto.getContent());

        //  3.2 关联文章内容中的图片和素材关系
        if (CollectionUtils.isNotEmpty(materials)) {
            saveRelativeMaterlAndArticle(materials, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }
        //  3.3 关联文章封面中的图片和素材关系  封面可能是选择自动或者是无图
        saveRelativeInfoForCover(dto, materials, wmNews);

        return ResponseResult.okResult();
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult delNew(Integer id) {
        //校验参数
        if(id==null)CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"文章id是必须的");
        //查询
        WmNews wmNews = wmNewsMapper.selectById(id);
        if(ObjectUtils.isNull(wmNews))CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"没找到");
        //判断文章状态，若是发布则无法删除
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())&&wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP))
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布无法删除");
        //清楚素材关联状态
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaUpdate().eq(WmNewsMaterial::getNewsId,id));
        //删除
        removeById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult addNew(Integer id) {
        //校验参数
        if(id==null)CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"文章id是必须的");
        //查询
        WmNews wmNews = wmNewsMapper.selectById(id);
        if(ObjectUtils.isNull(wmNews))CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"没找到");
        //响应结果
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(webSite);
//        ResponseResult<WmNews> wmNewsResponseResult = new ResponseResult<>();
//        wmNewsResponseResult.setHost(webSite);
//        wmNewsResponseResult.setData(wmNews);
//        wmNewsResponseResult.setCode(200);
        return responseResult;
    }

    /**
     * 【3.3】 关联文章封面中的图片和素材关系
     *
     * @param dto       前端用户选择封面信息数据
     * @param materials 从内容中解析的图片列表
     * @param wmNews    文章ID
     */
    private void saveRelativeInfoForCover(WmNewsDTO dto, List<String> materials, WmNews wmNews) {
        // 前端用户选择的图
        List<String> images = dto.getImages();
        // 自动获取封面 ****
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            int materialSize = materials.size();
            if (materialSize > 0 && materialSize <= 2) {  // 单图
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else if (materialSize > 2) { // 多图
                images = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {  // 无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if (images != null && images.size() > 0) {
                // 将图片集合 转为字符串  url1,url2,url3
                wmNews.setImages(imageListToStr(images));
            }
            updateById(wmNews);
        }
        // 保存图片列表和素材的关系
        if (images != null && images.size() > 0) {
            images = images.stream().map(x -> x.replace(webSite, "")
                    .replace(" ", "")).collect(Collectors.toList());
            saveRelativeMaterlAndArticle(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    //关联文章内容素材和文章
    private void saveRelativeMaterlAndArticle(List<String> materials, Integer id, Short type) {
        List<Integer> integers = wmMaterialMapper.selectRelationsIds(materials, WmThreadLocalUtils.getUser().getId());
        if (CollectionUtils.isEmpty(integers) || integers.size() < materials.size())
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "缺失资源，文章保存失败");
        wmNewsMaterialMapper.saveRelations(integers, id, type);
    }

    //关联文章封面素材和文章
    private void saveRelativeForCoverMaterlAndArticle(List<String> materials, Integer id, Short type) {
        List<Integer> integers = wmMaterialMapper.selectRelationsIds(materials, WmThreadLocalUtils.getUser().getId());
        if (CollectionUtils.isEmpty(integers) || integers.size() < materials.size())
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "缺失资源，文章保存失败");
        wmNewsMaterialMapper.saveRelations(integers, id, type);
    }

    private List<String> parseContentImages(String content) {
        List<Map> list = JSON.parseArray(content, Map.class);
        List<String> stringList = list.stream().filter(listq -> listq.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE))
                .map(map1 -> (String) map1.get("value"))
                .map(map2 -> map2.replace(webSite, "").replace(" ", ""))
                .distinct()
                .collect(Collectors.toList());
        return stringList;

    }

    /**
     * 图片列表转字符串，并去除图片前缀
     *
     * @param images 图片列表
     */
    private String imageListToStr(List<String> images) {
        String collect = images.stream().map(url -> url.replace(webSite, ""))
                .collect(Collectors.joining());
        return collect;
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //判断参数合法性
        if(dto==null||dto.getId()==null||dto.getEnable()==null||
                (!dto.getEnable().equals(WemediaConstants.WM_NEWS_UP)&&!dto.getEnable().equals(WemediaConstants.WM_NEWS_DOWN)))
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数异常");
        //查找文章
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if(wmNews==null)CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        //判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()))CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"为发布的文章不能上下架");
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        return ResponseResult.okResult();
    }

    private void saveWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
      //  wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        if (wmNews.getId() == null) save(wmNews);
        else {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }
}
